<template>
  <app-dialog-form
    :title="`${props.cateId ? '编辑' : '添加'}分类`"
    :confirm="handleSubmit"
    width="700px"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item
        label="父级"
        prop="pid"
      >
        <el-select
          v-model="formData.pid"
          placeholder="请选择父级"
        >
          <el-option
            v-for="item in catePidOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类名称"
        prop="cate_name"
      >
        <el-input
          v-model="formData.cate_name"
          placeholder="请输入分类名称"
        />
      </el-form-item>
      <el-form-item
        label="分类图标(180*180)"
        prop="pic"
      >
        <app-image-upload-input
          v-model="formData.pic"
        />
      </el-form-item>
      <el-form-item
        label="排序"
        prop="sort"
      >
        <el-input-number
          v-model="formData.sort"
          :min="0"
          label="请输入排序"
        />
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="formData.is_show">
          <el-radio
            :label="1"
          >
            显示
          </el-radio>
          <el-radio
            :label="0"
          >
            隐藏
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import type { ISelectOptions } from '@/api/types/form'
import { ElMessage } from 'element-plus'
import type { CategoryForm } from '@/api/types/product'
import { saveCategory, getCategory, getCategoryParentOptions } from '@/api/product'

const props = defineProps({
  cateId: { // 编辑的商品分类 ID
    type: Number as PropType<number | null>,
    default: null
  }
})

interface EmitsType {
  (e: 'update:cate-id', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formLoading = ref(false)
const formData = ref<CategoryForm>({
  cate_name: '',
  pid: undefined,
  sort: 1,
  pic: undefined,
  is_show: 1
})
const catePidOptions = ref<ISelectOptions[]>([])

const formRules = ref<IFormRule>({
  pid: [
    { required: true, message: '请选择父级', trigger: 'blur' }
  ],
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
})

formLoading.value = true
const handleDialogOpen = () => {
  formLoading.value = true
  Promise.all([loadCategoryParentOptions(), loadCategory()]).finally(() => {
    formLoading.value = false
  })
}

const loadCategoryParentOptions = async () => {
  const data = await getCategoryParentOptions()
  catePidOptions.value = data
}

const loadCategory = async () => {
  if (!props.cateId) {
    return
  }
  const dataRules = await getCategory(props.cateId)

  dataRules.forEach(item => {
    (formData.value as any)[item.field] = item.value
  })
}

const handleDialogClosed = () => {
  emit('update:cate-id', null)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  await saveCategory(formData.value, props.cateId)
  emit('success')
  ElMessage.success('保存成功')
}

</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
